#include "binstore.h"
#include <tchar.h>
#include "TempleteFea.h"

void write_senbin(FILE* file,vector<sentence_inter>& sens)
{
	vector<sentence> binout_sens;
	binout_sens.resize(sens.size());
	int all_num = sens.size();

	int ioffset_span = 0;
	for (int i=0;i<sens.size();i++)
	{
		sentence_inter& fwi = sens[i];
		sentence& wb = binout_sens[i];
		wb.l = fwi.label.size();
		wb.labels =fwi.label;
		wb.word_feas.resize(wb.l);
		wb.word_feas_num.resize(wb.l);
		for(int c=0;c<wb.l;c++)
		{
			wb.word_feas[c] = (span_feature*)ioffset_span;
			wb.word_feas_num[c] = fwi.word_feas[c].size();
			ioffset_span+=fwi.word_feas[c].size();
		}
	}
	//-------------------
	long  stf = ftell(file);
	fwrite(&all_num,sizeof(int),1,file);
	for (int i=0;i<sens.size();i++)
	{
		sentence& wb = binout_sens[i];
		fwrite(&wb.l,sizeof(int),1,file);
		fwrite(&wb.labels[0],sizeof(int),wb.l,file);
		fwrite(&wb.word_feas_num[0],sizeof(int),wb.l,file);
		for(int c=0;c<wb.l;c++) {
			int offs = (int)wb.word_feas[c];
			fwrite(&offs,sizeof(int),1,file);
		}
	}
	char *endcfgtag = "ENDTAG";
	fwrite(endcfgtag,sizeof(char),6,file);
	int ttw=0;
	fwrite(&ioffset_span,sizeof(int),1,file);
	for (int i=0;i<sens.size();i++)
	{
		sentence_inter& fwi = sens[i];
		for(int c=0;c<fwi.l;c++)
			for(int j=0;j<fwi.word_feas[c].size();j++)
			{
				fwrite(&fwi.word_feas[c][j],sizeof(span_feature),1,file);
				ttw++;
			}
	}
	char *endsentag = "ENDSEN";
	fwrite(endsentag,sizeof(char),6,file);
	assert_loc(ttw==ioffset_span);
}

void read_senbin(char* path,vector<sentence>& sens,memPool<char>& vec_pools)
{
	FILE* fd = fopen(path,"rb");
	int ic=0;
	fseek(fd,0,SEEK_END);
	int sz = ftell(fd);
	fseek(fd,0,SEEK_SET);
	vec_pools.alloc(sz);
	char* buf=(char*)vec_pools;
	fread(buf,sz,1,fd);
	assert_loc(sz==ftell(fd));
	fclose(fd);

	int all_num = *(int*)buf; buf+=4;
	sens.resize(all_num);
	for(int ls=0;ls<all_num;ls++) {
		sentence& wb = sens[ls];

		wb.l=  *(int*)buf; buf+=4;
		wb.labels.resize(wb.l);
		for(int c=0;c<wb.l;c++) {
			wb.labels[c]=*(int*)buf;
			buf+=4;
		}

		wb.word_feas_num.resize(wb.l);
		for(int c=0;c<wb.l;c++) {
			wb.word_feas_num[c]=*(int*)buf;
			buf+=4;
		}

		wb.word_feas.resize(wb.l);
		for(int c=0;c<wb.l;c++) {
			wb.word_feas[c]=(span_feature*)*(int*)buf;
			buf+=4;
		}
	}
	char endcfgtag[7];
	memcpy(endcfgtag,buf,6);endcfgtag[6]=0;
	assert_loc(!strcmp(endcfgtag,"ENDTAG"));
	buf+=6;

	int ioffset_span=*(int*)buf;buf+=4;
	span_feature* span_pool = (span_feature*)buf;
	buf+=ioffset_span*sizeof(span_feature);

	char endsentag[7];
	memcpy(endsentag,buf,6);endsentag[6]=0;
	assert_loc(!strcmp(endsentag,"ENDSEN"));
	


	for(int ls=0;ls<all_num;ls++) {
		sentence& wb = sens[ls];
		for(int c=0;c<wb.l;c++) {
			int xoff = (int)wb.word_feas[c];
			wb.word_feas[c]=span_pool+xoff;
		}
	}
}
